import axios from 'axios';
import store from '@/store';

let base = 'http://localhost:8089';
// let base = 'http://api.deveb.cn:8088';

// 全局axios默认值
// axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/json,application/x-www-form-urlencoded';
// axios.defaults.withCredentials = true;

const instance = axios.create({
	baseURL: base,
	timeout: 5000
});

// 在实例创建后设置或改变默认值
// instance.defaults.headers.post['Content-Type'] = 'application/json'

// http request 拦截器
instance.interceptors.request.use(config => {
    // console.log('))) '+store.state.token);
	// 判断是否存在token，如果存在的话，则每个http header都加上token
	if(store.state.token) {
        config.headers.Authorization = store.state.token;
	}
	return config
}, err => {
	return Promise.reject(err)
})

// http response 拦截器
instance.interceptors.response.use(response => {
	return response
}, error => {
	if (error.response) {
		switch (error.response.status) {
			case 401:
				// 返回 401 清除token信息并跳转到登录页面
				store.commit(types.LOGOUT);
				router.replace({
					path: 'login',
					query: {redirect: router.currentRoute.fullPath}
				})
		}
	}
	// 返回接口返回的错误信息
	return Promise.reject(error.response.data)
})

//export const requestLogin = params => {return axios.post(`${base}/test`, params).then(res => res.data);};

// 登录
// export const requestLogin = params => {
//     return instance.post(`/auth`, params).then(res => res.data);
// };

export default instance;